package com.qsxc.utils;

import com.alibaba.fastjson.JSONObject;
import com.qsxc.utils.wechat.WeChatTokenReq;
import com.qsxc.utils.wechat.WeChatTokenRsp;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.client.RestTemplate;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.List;

@Slf4j
public class WeChatUtil {
    private static String baseUrl = "http://10.5.1.183/wechatToken/services/";
    /**
     * 强制刷新微信accessToken
     */
    public final static String isRefresh = "1";

    private final static String OPENID_URL = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=APPSECRET&code=CODE&grant_type=authorization_code";

    /**
     * 获取openid
     *
     * @param appId
     * @param appSecret
     * @return
     */
    public static String getOpenId(String code, String appId, String appSecret) {
        String openid = null;
        if (StringUtil.isEmpty(appId) || StringUtil.isEmpty(appSecret) || StringUtil.isEmpty(code)) {
            return openid;
        }

        try {
            String url = OPENID_URL.replace("APPID", appId).replace("APPSECRET", appSecret).replace("CODE", code);
            JSONObject jsonObject = JSONObject.parseObject(getRetrunString(url, "GET"));
            log.info("getOpenId:" + jsonObject);
            boolean containsValue = jsonObject.containsKey("openid");
            if (containsValue) {
                openid = jsonObject.getString("openid");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return openid;
    }

    private static String getRetrunString(String url, String method) {
        HttpURLConnection connection = null;
        BufferedReader in = null;
        StringBuilder builder = new StringBuilder();
        try {
            connection = (HttpURLConnection) new URL(url).openConnection();
            // 设置连接超时时间，单位毫秒
            connection.setConnectTimeout(2000);
            // 设置读取数据超时时间，单位毫秒
            connection.setReadTimeout(2000);
            // 是否打开输出流 true|false
            connection.setDoOutput(true);
            // 是否打开输入流true|false
            connection.setDoInput(true);
            // 提交方法POST|GET
            connection.setRequestMethod(method);
            // 是否缓存true|false
            connection.setUseCaches(false);
            // 打开连接端口
            connection.connect();

            in = new BufferedReader(new InputStreamReader(connection.getInputStream(), "utf-8"));
            String line = in.readLine();
            while (null != line) {
                builder.append(line);
                line = in.readLine();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (in != null) {
                    in.close();
                    in = null;
                }
                if (connection != null) {
                    connection.disconnect();
                    connection = null;
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        log.info("wechat callback:" + builder.toString());
        return builder.toString();
    }

    /**
     * 获取access_token 此接口的access_token 是接口基础调用access_token 不是网页授权access_token
     *
     * @param appId
     * @param appSecret
     * @param isRefresh true 强制刷新
     * @return
     */
    public static String getAccessToken(String appId, String appSecret, String isRefresh) {
        String accessToken = null;
        if (StringUtil.isEmpty(appId) || StringUtil.isEmpty(appSecret)) {
            return accessToken;
        }
        String postUrl = baseUrl + "weChat/getWeChatToken.ws";
        WeChatTokenReq param = new WeChatTokenReq();
        param.setAppId(appId);
        param.setAppScript(appSecret);
        if (WeChatUtil.isRefresh.equals(isRefresh)) {
            param.setForceRefresh(WeChatUtil.isRefresh);
        }
        RestTemplate restTemplate = new RestTemplate(HttpUtil.getRequestFcatory());
        WeChatTokenRsp result = restTemplate.postForObject(postUrl, param, WeChatTokenRsp.class);

        log.info("获取AccessToken========" + result);

        if (WeChatTokenRsp.success.equals(result.getCode()) && !StringUtil.isEmpty(result.getToken())) {
            accessToken = result.getToken();
        }
        return accessToken;
    }

    /**
     * 获取jsapi_ticket
     * jsapi_ticket是公众号用于调用微信JS接口的临时票据
     *
     * @param appId
     * @param appSecret
     * @param isRefresh 1 强制刷新 可为空
     * @return
     */
    public static String getJspapiTicket(String appId, String appSecret, String isRefresh) {
        String jsapi_ticket_url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=ACCESS_TOKEN&type=jsapi";
        String jsapiTicket = null;
        if (StringUtil.isEmpty(appId) || StringUtil.isEmpty(appSecret)) {
            return jsapiTicket;
        }
        String accessToken = getAccessToken(appId, appSecret, isRefresh);
        // 如果请求成功
        if (!StringUtil.isEmpty(accessToken)) {
            String jsapiUrl = jsapi_ticket_url.replace("ACCESS_TOKEN", accessToken);
            RestTemplate restTemplate = new RestTemplate(HttpUtil.getRequestFcatory());

            JSONObject tjson = restTemplate.getForObject(jsapiUrl, JSONObject.class);
            log.info("getJspapiTicket========" + String.valueOf(tjson));
            if (null != tjson) {
                jsapiTicket = tjson.getString("ticket");
            }
        }
        return jsapiTicket;
    }

    public static RestTemplate getInstance(String charset) {
        RestTemplate restTemplate = new RestTemplate(HttpUtil.getRequestFcatory());
        List<HttpMessageConverter<?>> list = restTemplate.getMessageConverters();
        for (HttpMessageConverter<?> httpMessageConverter : list) {
            if (httpMessageConverter instanceof StringHttpMessageConverter) {
                ((StringHttpMessageConverter) httpMessageConverter).setDefaultCharset(Charset.forName(charset));
            }
        }
        return restTemplate;
    }
}
